#ifndef __GRAPH_HPP__
#define __GRAPH_HPP__

#include<unordered_map>
#include<vector>
#include<algorithm>
#include<iostream>
#include<unordered_set>
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef pair<int,int> PI;

vector<string> colorset={
    "black","green","blue","yellow","lightblue",
    "pink","purple","gray","beige","brown"
};

struct graph{
    vector<string> ns,color;
    vector<vector<string> > edgs;
    unordered_map<string,int> name_to_ind;
    graph()=default;
    graph(string filename){
        init(filename);
    }
    void init(string filename){
        ns.clear();color.clear();
        edgs.clear();name_to_ind.clear();
        FILE *fp=fopen(filename.c_str(),"r");
        if(fp==NULL){
            cerr<<"file no found";
            exit(-1);
        }
        int n;
        fscanf(fp,"%d",&n);
        char tmp1[100],tmp2[100],tmp3[100];
        ns.resize(n);
        color.resize(n);
        edgs.resize(n);
        for(int i=0;i<n;i++){
            fscanf(fp,"%s%s",tmp1,tmp2);
            ns[i]=tmp1;
            color[i]=tmp2;
            name_to_ind[ns[i]]=i;
            edgs[i].resize(n);
        }
        int m;
        fscanf(fp,"%d",&m);
        for(int i=0;i<m;i++){
            fscanf(fp,"%s%s%s",tmp1,tmp2,tmp3);
            edgs[name_to_ind[tmp1]]
                [name_to_ind[tmp2]]=tmp3;
            edgs[name_to_ind[tmp2]]
                [name_to_ind[tmp1]]=tmp3;
        }
        fclose(fp);
    }
    void write(string filename){
        string res;
        int n=ns.size();
        res+=to_string(n)+'\n';
        for(int i=0;i<n;i++){
            res+=ns[i]+' '+color[i]+'\n';
        }
        string es;
        int m=0;
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                if(edgs[i][j]!=""){
                    es+=ns[i]+' '+ns[j]+' '+edgs[i][j]+'\n';
                    ++m;
                }
            }
        }
        res+=to_string(m)+'\n'+es;
        FILE* fp=fopen(filename.c_str(),"w+");
        fprintf(fp,"%s",res.c_str());
        fclose(fp);
    }
    void drawedg(const VVI &ed){
        int n=edgs.size();
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                if(edgs[i][j]!=""){
                    edgs[i][j]=edgs[j][i]=colorset[ed[i][j]];
                }
            }
        }
    }
};

#endif
